<?php

namespace app\controllers;


use app\models\Area;
use app\tools\Curl;
use app\tools\Map;
use app\tools\Re;
use Yii;

class AreaController extends BaseController {

  public function actionGetArea() {
    $lng = Yii::$app->request->post('lng', '');
    $lat = Yii::$app->request->post('lat', '');
    $location = $lng.','.$lat;
    $res = Map::getArea($location);
    $area_code = $res->adcode * 1000000;
    $area_info = Area::find()->where(['area_code' => $area_code])->one();
    $data = [
      'province_id' => $area_info->parentArea->parentArea->id,
      'province_name' => $area_info->parentArea->parentArea->name,
      'city_id' => $area_info->parentArea->id,
      'city_code' => $area_info->parentArea->area_code/1000000,
      'city_name' => $area_info->parentArea->name,
      'area_id' => $area_info->id,
      'area_name' => $area_info->name,
      'area_code' => $area_info->area_code/1000000,
      'street' => $res->streetNumber->street,
      'number' => $res->streetNumber->number,
    ];
    return Re::data(['data' => $data]);
  }

  //省市区一起返回
  public function actionList(){
    $p_list = Area::find()->where(['parent_id' => 0])->andWhere("short_name not in ('香港', '澳门', '台湾')")->select("area_code,name")->all();
    $province_list = [];
    if ($p_list) {
      foreach ($p_list as $k=>$v) {
        $index = $v->area_code/1000000;
        $province_list[$index] = $v->name;
      }
    }
    $c_list = Area::find()->where(['level' => 1])->andWhere('area_code <> 0')->select("area_code,name")->all();
    $city_list = [];
    if ($c_list) {
      foreach ($c_list as $k1=>$v1) {
        $index1 = $v1->area_code/1000000;
        $city_list[$index1] = $v1->name;
      }
    }
    $a_list = Area::find()->where(['level' => 2])->andWhere('area_code <> 0')->andWhere("name <> '市辖区'")->select("area_code,name")->all();
    $county_list = [];
    if ($a_list) {
      foreach ($a_list as $k2=>$v2) {
        $index2 = $v2->area_code/1000000;
        $county_list[$index2] = $v2->name;
      }
    }
    $data = [
      'province_list' => $province_list,
      'city_list' => $city_list,
      'county_list' => $county_list,
    ];
    return Re::data(['data' => $data]);
  }
}
